package com.epoch.wx.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.epoch.wx.annotaion.IgnoreAuth;
import com.epoch.wx.dao.WxToken;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

public class AuthorizationInterceptor implements Interceptor{

	public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
    public static final String LOGIN_TOKEN_KEY = "X-Nideshop-Token";
	
    @Override
	public void intercept(Invocation inv) {
		String viewPath = inv.getViewPath();
		if(viewPath.startsWith("/api")) {
			IgnoreAuth annotation = inv.getMethod().getAnnotation(IgnoreAuth.class);
			HttpServletRequest request = inv.getController().getRequest();
			if(null != annotation) {
				String token = request.getHeader(LOGIN_TOKEN_KEY);
				//如果header中不存在token，则从参数中获取token
		        if (StringUtils.isBlank(token)) {
		            token = request.getParameter(LOGIN_TOKEN_KEY);
		        }
		        if(StringUtils.isEmpty(token)) {
					Map<String, Object> obj = new HashMap<String, Object>();
			        obj.put("errno", 1);
			        obj.put("errmsg", "请先登录"); 
			        obj.put("code", 401);
			        inv.getController().renderJson(obj);
			        return;
				}
		        //验证token是否过期，注意：这一步和上一步，如果微信端返回了请登录，一定调用微信的清除token的clear方法
		        WxToken wxToken = WxToken.dao.findFirst("select * from wx_token where token = ?",token);
		        if (null == wxToken || wxToken.getDate(WxToken.EXPIRE_TIME).getTime() < System.currentTimeMillis()) {
		        	Map<String, Object> obj = new HashMap<String, Object>();
			        obj.put("errno", 1);
			        obj.put("errmsg", "token已过期，请重新登录"); 
			        obj.put("code", 401);
			        inv.getController().renderJson(obj);
			        return;
		        }
	        	request.setAttribute(LOGIN_USER_KEY, wxToken.getStr(WxToken.USER_ID));
			}
		}
		inv.invoke();
	}

}
